<template>
  <basic-container>
    <div>
      <el-form ref="form" searchform :model="form" label-width="80px">
        <el-row>
          <el-col span="5" style="min-width:150px">
            <div class="text" style="width: 30%">订单:</div>
            <el-select
              id="id-creativereport-bc-notfoundcreativeperformance-submitForm"
              size="mini"
              v-model="form.offerId"
              placeholder="请选择订单"
              clearable
              ref="performPlatform" @change="submitForm" style="width: 60%">
              <el-option
                v-for="item in offerList"
                :key="item.offerId"
                :label="item.offerName"
                :value="item.offerId">
              </el-option>
            </el-select>
          </el-col>
          <el-col span="5" style="min-width:150px">
            <div class="text" style="width: 30%">素材名称:</div>
            <el-input
              id="id-creativereport-bc-notfoundcreativeperformance-submitForm-two"
              size="mini"
              v-model="form.name"
              placeholder="请输入素材名称"
              @keyup.enter.native="submitForm" style="width: 60%">
            </el-input>
          </el-col>
          <el-col span="5" style="min-width:150px">
            <div class="text" style="width: 30%">媒体:</div>
            <el-select
              id="id-creativereport-bc-notfoundcreativeperformance-submitForm-3"
              size="mini"
              v-model="form.platform"
              placeholder="请选择媒体"
              clearable
              ref="performPlatform" @change="submitForm" style="width: 60%">
              <el-option
                v-for="item in platformList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-col>
          <el-col span="5" style="min-width:150px">
            <div class="text" style="width: 30%">投放地区:</div>
            <el-select id="id-creativereport-bc-notfoundcreativeperformance-submitForm-nationList"
                       v-model="form.nationList" size="mini" multiple clearable filterable placeholder="请选择"
                       ref="performNation" @change="submitForm" style="width: 60%">
              <el-option
                v-for="(item,index) in nationList"
                :key="index"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-col>
          <el-col span="5" style="min-width:150px">
            <div class="text" style="width: 30%">更新时间:</div>
            <el-date-picker
              id="id-creativereport-bc-notfoundcreativeperformance-updateTimeRange"
              style="width: 60%"
              size="mini"
              v-model="form.updateTimeRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              ref="performTime" @change="submitForm" >
            </el-date-picker>
          </el-col>
          <el-col span="4" style="min-width: 160px;display:flex;justify-content:flex-end">
            <!--<el-tooltip class="item" effect="dark" content="展开全部" placement="top">-->
              <!--<el-button :class="upIcon" disabled class="search-circle" @click="unfoldIcon" style="margin-right: 10px"></el-button>-->
            <!--</el-tooltip>-->
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button id="id-creativereport-bc-notfoundcreativeperformance-resetSearch"
                         :class="emptyIcon" class="search-circle" @click="searchReset"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-creativereport-bc-notfoundcreativeperformance-submitForm-6"
                         type="primary" icon="el-icon-search" size="small" @click="submitForm" style="margin-right: 0">搜索</el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-button id="id-creativereport-bc-notfoundcreativeperformance-showView-image"
                 type="primary" size="mini" :plain="(selectType == 1)" @click="showView(0)">图 片</el-button>
      <span style="padding-left: 20px;"></span>
      <el-button id="id-creativereport-bc-notfoundcreativeperformance-showView-video"
                 type="primary" size="mini" :plain="(selectType == 0)" @click="showView(1)">视 频</el-button>
    </div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @sort-change="sortChange"
    >
      <template slot-scope="{ row }" slot="assetUrl">
        <div @click="handleMediaPreview(row)">
          <img
            v-show="getMediaType(row) == 'image'"
            width="100%"
            :src="row.assetUrl"
          />
          <video
            v-show="getMediaType(row) == 'video'"
            :src="row.assetUrl"
            style="width: 100%"
          ></video>
        </div>
      </template>
      <template slot-scope="{ row }" slot="ads">
        <div>
          {{ countAds(row) }}
        </div>
      </template>
      <template slot-scope="{ row }" slot="ctr">
        <div>{{ row.ctr }}%</div>
      </template>
      <template slot-scope="{ row }" slot="cvr">
        <div>{{ row.cvr }}%</div>
      </template>
    </avue-crud>

    <el-dialog
      title="预览"
      :visible="mediaPreviewDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
      :append-to-body="true"
      style="text-align: center"
    >
      <img
        v-if="mediaPreviewDialog.dialogType === 'image'"
        :style="previewStyle()"
        :src="mediaPreviewDialog.previewUrl"
      />
      <video
        ref="video"
        v-if="mediaPreviewDialog.dialogType === 'video'"
        :src="mediaPreviewDialog.previewUrl"
        :style="previewStyle()"
        controls="controls"
      ></video>
    </el-dialog>

  </basic-container>
</template>

<script>
import {getList, getOfferList} from "@/api/offer/notfoundcreativeperformance";
import { getSysDictList } from "@/api/system/dict";
import {findObject} from "@/util/util";
import { mapGetters } from "vuex";
import Moment from "moment";

export default {
  data() {
    return {
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      selectType: 0,
      offerList: [],
      platformList: [],
      nationList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Moment(Moment(new Date()).format('YYYY-MM-DD')).toDate();
        },
        shortcuts: [{
          text: '过去三十天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "months").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去十四天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(14, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去七天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(7, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '昨天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, start]);
          }
        }]
      },
      form: {
        offerId: '',
        platform: null,
        beginDate: null,
        endDate: null,
        name: null,
        nationList: [],
        updateTimeRange: [],
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        selection: false,
        menu: false,
        menuLeft: false,
        dialogClickModal: false,
        defaultSort: {prop: 'spend', order: 'descending'},
        column: [
          {
            label: "素材",
            prop: "assetUrl",
            rules: [
              {
                required: true,
                message: "请输入素材",
                trigger: "blur",
              },
            ],
            slot: true,
          },
          {
            label: "名称",
            prop: "name",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "媒体",
            prop: "platform",
            slot: true,
          },
          {
            label: "投放地区",
            prop: "countryList",
            multiple: true,
            type: 'select',
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
          {
            label: "订单名",
            prop: "offerName",
          },
          {
            label: "关联广告数",
            prop: "ads",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "花费",
            prop: "spend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "曝光",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width:120,
            sortable: 'custom',
          },
          {
            label: "点击",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
          {
            label: "安装",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
        ],
      },
      data: [],
      sortList: [{name: 'spend', orderBy: 'desc'}],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    //window.addEventListener('keyup', this.submitForm) //监听键盘事件
    this.form.updateTimeRange = [Moment().subtract("days", 7).format("yyyy-MM-DD"), Moment().subtract("days", 1).format("yyyy-MM-DD")];
    this.buildSearch();

    getOfferList().then(res=>{
      this.offerList = res.data.data;
    });
    this.refresh();
  },
  methods: {
    unfoldIcon(){
      if (this.upIcon === 'el-icon-arrow-down'){
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      }else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      let type = this.getMediaType(row);
      if(type == null || type == '') {
        return;
      }
      this.mediaPreviewDialog.previewUrl = row.assetUrl;
      this.mediaPreviewDialog.dialogType = type;
      this.mediaPreviewDialog.dialogVisible = true;
    },
    /**
     * 图片排序
     * @param val
     */
    sortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if(orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.onLoad(this.page);
    },
    refresh() {
      getSysDictList("platforms,nation").then((map) => {
        this.platformList = map['platforms']
        this.nationList = map['nation'];
        let column = findObject(this.option.column,'countryList','prop');
        if(column != null) {
          column.dicData = this.nationList;
        }
      });
    },
    /**
     * 统计当前素材跑了多少个广告
     * @param row
     * @returns {string}
     */
    countAds(row) {
      if(!row.ads || row.ads == '') {
        return 0;
      }
      let adsArr = (row.ads || '').split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },
    buildSearch() {
      if (this.form.updateTimeRange != null && this.form.updateTimeRange.length == 2) {
        this.form.beginDate = this.form.updateTimeRange[0];
        this.form.endDate = this.form.updateTimeRange[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.query = {...this.form};
      this.query.nationList = this.form.nationList.join(',');
      delete this.query.updateTimeRange;
    },
    submitForm() {
      this.buildSearch();
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    getMediaType(row) {
      if(row.assetUrl != null && row.assetUrl != '') {
        if(row.type == 0) {
          return 'image';
        }
        if(row.type == 1) {
          return 'video';
        }
      }
      return '';
    },
    dialogType(val) {
      let type = '';
      let url = val;
      if(url != null) {
        url = url.split('?')[0];
      }
      let urlTail = ((url != null && url.indexOf('.') >= 0) ? (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();
      if(urlTail == '') {
        return type;
      }

      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },
    searchReset() {
      this.form = {
        offerId: null,
        platform: null,
        beginDate: "",
        endDate: "",
        name: '',
        nationList: [],
        updateTimeRange: [],
      };
      this.submitForm();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    showView(type) {
      if (this.selectType != type) {
        this.selectType = type;
        this.page.currentPage = 1;
        this.onLoad(this.page);
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      let sortList = this.sortList;
      getList(
        this.page.currentPage,
        this.page.pageSize,
        Object.assign({}, params, this.query, {type: this.selectType},{sortList: JSON.stringify(sortList)})
      ).then((res) => {
        let data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data.forEach(row=>{
          if(row.countryList != null) {
            let countryList = row.countryList.split(',');
            let set = new Set();
            countryList.forEach(c=>{
              set.add(c);
            });
            row.countryList = Array.from(set).join(',');
          }
        });
      },(error)=>{
        this.$message.warning("数据加载出错！");
      }).finally(()=>{
        this.loading = false;
      });
    },
  },
};
</script>

<style>
.search-circle{
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}
</style>
